package com.wzt.org.service.impl;

import com.wzt.base.constant.BaseConstants;
import com.wzt.base.service.impl.AutoAuditImpl;
import com.wzt.base.service.impl.BaseServiceImpl;
import com.wzt.base.util.AjaxResponse;
import com.wzt.org.domain.Employee;
import com.wzt.org.domain.Shop;
import com.wzt.org.domain.ShopAuditLog;
import com.wzt.org.mapper.EmployeeMapper;
import com.wzt.org.mapper.ShopAuditLogMapper;
import com.wzt.org.mapper.ShopMapper;
import com.wzt.org.service.IShopService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.Date;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author wzt
 * @since 2022-09-01
 */
@Service
public class ShopServiceImpl extends BaseServiceImpl<Shop> implements IShopService {
    @Autowired
    private ShopMapper shopMapper;
    @Autowired
    private EmployeeMapper employeeMapper;
    @Autowired
    private AutoAuditImpl autoAudit;
    @Autowired
    private ShopAuditLogMapper logMapper;

    @Override
    @Transactional(rollbackFor = {})
    public void register(Shop shop) {
        //1 校验
        validate(shop);

        //2 校验完成后保存店铺信息
        // 设置店铺注册时间
        shop.setRegisterTime(new Date());
        shopMapper.insert(shop);
        /**
         * 保存店铺管理员信息：
         *  (1)直接使用原来的店铺管理员信息[选用]
         *  (2)不让入驻，直接登录，在后台添加店铺
         */
        //3 通过店铺注册的管理员的名字到数据库中去查询是否已经存在了这个管理员
        Employee admin = shop.getAdmin();
        String adminName = admin.getUsername();
        Employee adminInDataBase = employeeMapper.loadByUsername(adminName);
        // 如果这个管理员不存在,则添加将该管理员添加到数据库中
        if (adminInDataBase == null) {
            admin.setState(BaseConstants.Employee.STATE_UNACTIVATED);
            employeeMapper.insert(admin);
        }

        //4 为注册店铺设置管理员并更新
        shop.setAdminId(adminInDataBase == null ? admin.getId() : adminInDataBase.getId());
        shopMapper.update(shop);

        //5 进行自动审核，根据审核结果需要修改店铺状态
        String authText = shop.getName() + " " + shop.getAddress();
        // 获取审核结果
        AjaxResponse response = autoAudit.audit(authText, null, null);
        if (response.getSuccess()) {
            // 如果审核通过，设置店铺状态为待激活
            shop.setState(BaseConstants.Shop.STATE_WAIT_ACTIVE);
        } else {
            // 否则设为驳回
            shop.setState(BaseConstants.Shop.STATE_REJECT_AUDIT);
        }
        shopMapper.update(shop);

        //6 添加到审核日志中
        ShopAuditLog auditLog = new ShopAuditLog();
        auditLog.setState(response.getSuccess() ? 1 : 0);
        auditLog.setShopId(shop.getId());

        //没有审核人，因为是自动审核，但是有审核时间
        auditLog.setAuditTime(new Date());
        auditLog.setNote(response.getSuccess() ? "审核通过!" : "失败," + response.getMessage());
        logMapper.insert(auditLog);
    }

    private void validate(Shop shop) {
        // null检验
        // 店铺不能为空
        if (shop == null) {
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        }
        // 店铺名不能为空
        if (StringUtils.isEmpty(shop.getName())) {
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        }
        // 店铺必须有管理员
        if (shop.getAdmin() == null) {
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        }
        // 店铺管理员的名字和密码不能为空
        if (StringUtils.isEmpty(shop.getAdmin().getUsername()) ||
                StringUtils.isEmpty(shop.getAdmin().getPassword()) || StringUtils.isEmpty(shop.getAdmin().getConfirmPassword())) {
            throw new RuntimeException("系统错误！请输入相关信息后再操作");
        }

        // 比对两次密码是否一致
        if (!shop.getAdmin().getPassword().trim().equals(shop.getAdmin().getConfirmPassword().trim())) {
            throw new RuntimeException("两次密码不一致");
        }

        // 店铺不能是已经存在的
        Shop shopByDb = shopMapper.loadByName(shop.getName());
        if (shopByDb != null) {
            throw new RuntimeException("该店铺已经存在！");
        }
    }
}
